#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--){
        LL p,a,b,c;cin>>p>>a>>b>>c;
        if(p%a==0||p%b==0||p%c==0){
            cout<<"0"<<"\n";
        }
        else{
            LL k1,k2,k3;
            if(p<a){
                k1=0;
            }
            else k1=p/a+1;
            if(p<b){
                k2=0;
            }
            else k2=p/b+1;
            if(p<c){
                k3=0;
            }
            else k3=p/c+1;
            LL t1=k1*a%p;LL t2=k2*b%p;LL t3=k3*c%p;
            if(k1==0) t1=a-p;
            if(k2==0) t2=b-p;
            if(k3==0) t3=c-p;
            cout<<min(t1,min(t2,t3))<<"\n";
        }
  }
return 0;
}
